package com.ruoyi.file.service;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.errors.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.nacos.common.utils.IoUtils;
import com.ruoyi.file.config.MinioConfig;
import com.ruoyi.file.utils.FileUploadUtils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;

/**
 * Minio 文件存储
 *
 * @author ruoyi
 */
@Primary
@Service
@ConfigurationProperties(prefix = "minio")
public class MinioSysFileServiceImpl implements ISysFileService {
//    @Autowired
//    private MinioConfig minioConfig;
//
//    @Autowired
//    private MinioClient client;


    /**
     * 服务地址
     */
    @Value("${minio.endpointUrl}")
    private String endpointUrl;

    /**
     * 用户名
     */
    @Value("${minio.accessKey}")
    private String accessKey;

    /**
     * 密码
     */
    @Value("${minio.secreKey}")
    private String secreKey;

    /**
     * 存储桶名称
     */
    @Value("${minio.bucketName}")
    private String bucketName;

    /**
     * Minio文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException,
            IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException  {
        String url = "";
        MinioClient build = MinioClient.builder().endpoint(endpointUrl).credentials(accessKey, secreKey).build();
        //检查桶是否存在
        if (build.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            System.out.println("桶存在");
        } else {
            //桶不存在则创建
            build.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
        //定义一个文件名称 : 文件上传的时候名称不能重复
        String s = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
        String fileName = UUID.randomUUID().toString().replace("-", "") + "." + s;
        build.putObject(
                PutObjectArgs.builder().bucket(bucketName).object(fileName).
                        stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build()
        );


        return endpointUrl + "/" + bucketName + "/" + fileName;
    }
}
